import utils from '@/utils/utils.js';

const _empty = (v) => {
	let tp = typeof v,
		rt = false;
	if (tp == "number" && String(v) == "") {
		rt = true
	} else if (tp == "undefined") {
		rt = true
	} else if (tp == "object") {
		if (JSON.stringify(v) == "{}" || JSON.stringify(v) == "[]" || v == null) rt = true
	} else if (tp == "string") {
		if (v == "" || v == "undefined" || v == "null" || v == "{}" || v == "[]") rt = true
	} else if (tp == "function") {
		rt = false
	}
	return rt
}

const calcCharactersNumber = (s) => {
	var l = 0;
	var a = s.split("");
	for (var i = 0; i < a.length; i++) {
		if (a[i].charCodeAt(0) < 299) {
			l++;
		} else {
			l += 2;
		}
	}
	return l;
}


const prePage = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}

const showToast = (title, icon = 'none', duration = 1500, mask = true) => {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}

// 11位时间戳转 年-月-日 时:分:秒
const getDate = (timestamp) => { //  getDate(1691824516) => 2023-8-12 15:15:16'
	var timestamp = timestamp;
	var d = new Date(timestamp * 1000); //根据时间戳生成的时间对象
	var date = (d.getFullYear()) + "-" +
		(d.getMonth() + 1) + "-" +
		(d.getDate()) + " " +
		(d.getHours() >= 10 ? d.getHours() : '0' + d.getHours()) + ":" +
		(d.getMinutes() >= 10 ? d.getMinutes() : '0' + d.getMinutes()) + ":" +
		(d.getSeconds() >= 10 ? d.getSeconds() : '0' + d.getSeconds());
	return date;
}

// 11位时间戳转 分:秒
const getDateHM = (timestamp) => { // getDateHM(1691824516) '15:15' =》15分：15秒
	var timestamp = timestamp;
	var d = new Date(timestamp * 1000); //根据时间戳生成的时间对象
	var date =
		(d.getHours() >= 10 ? d.getHours() : '0' + d.getHours()) + ":" +
		(d.getMinutes() >= 10 ? d.getMinutes() : '0' + d.getMinutes());
	return date;
}

//日期字符串转时间戳   调用strToTimestamp('2019-01-01') 或者 strToTimestamp('2019-01-01 15:30:30')都支持
const strToTimestamp = (str) => {
	var date = str;
	date = date.substring(0, 19);
	date = date.replace(/-/g, '/');
	var timestamp = parseInt(new Date(date).getTime() / 1000);
	return timestamp;
}

const today = () => { //获取当前时间戳
	var timestamp = parseInt(new Date().getTime() / 1000); // 当前时间戳
	return timestamp;
}


const countdownTime = (t) => { //倒计时   t = 剩余时间 ex: '3858024天16时40分0秒'
	let day = Math.floor(t / 86400);
	let date = '';
	if (day > 0) {
		date += day + "天";
		t = t - day * 86400;
	}
	let h = Math.floor(t / 3600);
	if (h > 0) {
		date += h + "时";
		t = t - h * 3600;
	}
	let i = Math.floor(t / 60);
	if (i > 0) {
		date += i + "分";
		t = t - i * 60;
	}
	date += t + "秒";
	return date;
}

const countdownTime1 = (t) => { //倒计时   t = 剩余时间  ex:'01:00:00'
	let day = Math.floor(t / 86400); //天
	let date = '';
	// if (day > 0) {
	// 	date += day + "天";
	// 	t = t - day * 86400;
	// }

	let h = Math.floor(t / 3600); //小时

	if (h > 0) {
		if (h.toString().length == 1) {
			date = date + 0 + h + ":"
			t = t - h * 3600;
		} else if (h.toString().length == 0) {
			date = date + 0 + 0 + ":"
			t = t - h * 3600;
		} else {
			date += h + ":";
			t = t - h * 3600;
		}

	} else {
		date += "00:";
	}

	let i = Math.floor(t / 60); //分钟
	if (i > 0) {
		if (i.toString().length == 1) {
			date = date + 0 + i + ":";
			t = t - i * 60;
		} else {
			date += i + ":";
			t = t - i * 60;
		}

	} else {
		date += "00:";
	}

	if (t.toString().length == 1) {
		date = date + "0" + t; //秒
	} else {
		date += t; //秒
	}
	return date;
}
const countdownTime2 = (t) => { //倒计时   t = 剩余时间  ex: '00:01:00:00'
	let day = Math.floor(t / 86400); //天
	let date = '';
	if (day > 0) {
		date += day + ":";
		t = t - day * 86400;
	} else {
		date += "00:";
	}

	let h = Math.floor(t / 3600); //小时

	if (h > 0) {
		if (h.toString().length == 1) {
			date = date + 0 + h + ":"
			t = t - h * 3600;
		} else if (h.toString().length == 0) {
			date = date + 0 + 0 + ":"
			t = t - h * 3600;
		} else {
			date += h + ":";
			t = t - h * 3600;
		}

	} else {
		date += "00:";
	}

	let i = Math.floor(t / 60); //分钟
	if (i > 0) {
		if (i.toString().length == 1) {
			date = date + 0 + i + ":";
			t = t - i * 60;
		} else {
			date += i + ":";
			t = t - i * 60;
		}

	} else {
		date += "00:";
	}

	if (t.toString().length == 1) {
		date = date + "0" + t; //秒
	} else {
		date += t; //秒
	}
	return date;
}



// 以下4个方法配合处理 =》 根据毫秒级时间戳获取计算当前时间后的显示 用于聊天页面
// 一分钟内 = 刚刚
// 一小时内 = xx分钟之前
// 今日 = 时：分
// 今天之前当年内 = 月-日 时：分
// 不属于当年 = 年-月-日 时：分

function formatDateTime(timeValue) { //参数为13位时间戳
	var date = new Date(timeValue);
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	m = m < 10 ? ('0' + m) : m;
	var d = date.getDate();
	d = d < 10 ? ('0' + d) : d;
	var h = date.getHours();
	h = h < 10 ? ('0' + h) : h;
	var minute = date.getMinutes();
	var second = date.getSeconds();
	minute = minute < 10 ? ('0' + minute) : minute;
	second = second < 10 ? ('0' + second) : second;
	// return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
	return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' +
		second; //这里注意由于把上行的 - 替换成中文 年月日  所以会导致下面timeChange方法中的substr的位数，之后如果替换为- 则需要对应修改timechange中的substr位数
};

//判断传入日期是否为昨天
function isYestday(timeValue) { //参数为13位时间戳
	var date = (new Date());
	//当前时间
	var today = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
	//今天凌晨
	var yestday = new Date(today - 24 * 3600 * 1000).getTime();
	return timeValue < today && yestday <= timeValue;
};

//判断传入日期是否属于今年
function isYear(timeValue) { //参数为13位时间戳
	var takeNewYear = formatDateTime(new Date()).substr(0, 4);
	//当前时间的年份
	var takeTimeValue = formatDateTime(timeValue).substr(0, 4);
	//传入时间的年份
	return takeTimeValue == takeNewYear;
}

//60000 1分钟 //3600000 1小时 //86400000 24小时 //对传入时间进行时间转换
const timeChange = (timeValue) => { //参数为13位时间戳
	var timeNew = Date.parse(new Date());
	//当前时间
	var timeDiffer = timeNew - timeValue;
	//与当前时间误差 var returnTime = '';
	if (timeDiffer <= 60000) {
		//一分钟内
		var returnTime = '刚刚';
	} else if (timeDiffer > 60000 && timeDiffer < 3600000) {
		//1小时内
		var returnTime = Math.floor(timeDiffer / 60000) + '分钟前';
	} else if (timeDiffer >= 3600000 && timeDiffer < 86400000 && isYestday(timeValue) === false) {
		//今日
		var returnTime = formatDateTime(timeValue).substr(12, 5);
	} else if (timeDiffer > 3600000 && isYestday(timeValue) === true) {
		//昨天
		// var returnTime = '昨天' + formatDateTime(timeValue).substr(11, 5);
		var returnTime = formatDateTime(timeValue).substr(5, 12);
	} else if (timeDiffer > 86400000 && isYestday(timeValue) === false && isYear(timeValue) === true) {
		//今年
		var returnTime = formatDateTime(timeValue).substr(5, 12);
	} else if (timeDiffer > 86400000 && isYestday(timeValue) === false && isYear(timeValue) === false) {
		//不属于今年
		var returnTime = formatDateTime(timeValue).substr(0,
			17); //这里目前的需求只需要显示到分即可,所以暂时substr 0,16 如果需要精确到秒则 substr 0,20
	}
	return returnTime;
}

// 以上4个方法配合处理 =》 根据毫秒级时间戳获取计算当前时间后的显示 用于聊天页面


const isWx = () => {
	var ua = navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == "micromessenger") {
		return true;
	}
	return false;
};



/**
 * 图像转Base64
 */
const getBase64Image = (img) => {
	var canvas = document.createElement("canvas");
	canvas.width = img.width;
	canvas.height = img.height;
	var ctx = canvas.getContext("2d");
	ctx.drawImage(img, 0, 0, img.width, img.height);
	var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
	var dataURL = canvas.toDataURL("image/" + ext);
	return dataURL;
}

//对象按字母顺序排序
const objKeySort = (obj) => {
	//排序的函数
	let newkey = Object.keys(obj).sort();
	let newObj = {};
	for (let i = 0; i < newkey.length; i++) {
		newObj[newkey[i]] = obj[newkey[i]];
	}
	return newObj;
}

//将对象转换为key=value格式，支持多个用&连接
const getSigns = (datas) => {
	let data = objKeySort(datas);
	let params = "";
	if (
		typeof data == "undefined" ||
		data == null ||
		typeof data != "object"
	) {
		return "";
	}
	for (var k in data) {
		params += (params.indexOf("=") != -1 ? "&" : "") + k + "=" + data[k];
	}
	return params;
}

//将请求的data参数先排序然后转换成key=value格式
const calcRequestParams = (obj) => {
	let sortedParams = objKeySort(obj);
	let getSignsParams = getSigns(sortedParams);
	return getSignsParams;
}

const navTo = (url) => {
	uni.navigateTo({
		url: url,
	});
}

const redirectTo = (url) => {
	uni.redirectTo({
		url: url,
	});

}

const navBack = (url) => {
	uni.navigateBack();
}

const copyFunc = (content) => {
	uni.setClipboardData({
		data: content,
		success: function() {
			utils.showToast('复制成功', 'none');
		}
	});
}

//获取小程序胶囊的位置以及宽高信息
const getMenuButtonBounding = () => {
	let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
	return menuButtonInfo;
}


//获取设备宽度
const getPageWidth = () => {
	let pageWidth = uni.getWindowInfo().screenWidth;
	return pageWidth;
}


//顶部元素与小程序胶囊居中的位置处理；
//备注 css 无法获取胶囊的信息  只能获取 顶部状态栏status-bar  所以使用js方式获取
const calcElementInfo = (vue, elementId) => {
	return new Promise((resolve, reject) => {
		//获取设备宽度
		let pageWidth = uni.getWindowInfo().screenWidth;
		//获取小程序胶囊按钮的位置信息
		let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
		let calcPtTop = menuButtonInfo.top + 3 + 'px'; // 配合居中显示 固定值改为3 - 20240730
		//获取设置icon的位置信息
		const elmt = uni.createSelectorQuery().in(vue);
		let calcTop, calcRight, calcElmtClientHeight;
		elmt.select(elementId).boundingClientRect(rect => {
			// console.log(rect,menuButtonInfo);
			calcTop = menuButtonInfo.top + (menuButtonInfo.height - rect.height) / 2 +
				'px'; //为了自定义区域与胶囊居中
			calcRight = pageWidth - menuButtonInfo.left + 6 + 'px'; //此处的6为固定值作为边距
			calcElmtClientHeight = menuButtonInfo.top + menuButtonInfo.height +
				'px'; //顶部固定区域下面section内容的marginTop

			let caHeight = uni.getStorageSync('calcElmtClientHeight');
			if (!caHeight) uni.setStorageSync('calcElmtClientHeight', calcElmtClientHeight);




			resolve({
				calcPtTop,
				calcTop,
				calcRight,
				calcElmtClientHeight
			})
		}).exec();




		//必须延时获取，否则bounding中的变量为undefined
		// setTimeout(()=>{
		// 	console.log('calcPtTop=',calcPtTop);
		// 	console.log('111calcTop=',calcTop);
		// 	console.log('calcRight=',calcRight);
		// 	resolve({calcPtTop,calcTop,calcRight})
		// },800)
	});
}


//将手机号4-7位替换成*
const calcPhoneNumber = (number) => {
	number = String(number);
	return number.replace(number.substring(3, 7), "****");
}



const imgUrl = (v) => {
	//等待之后正确的 修改这个方法  调用此方法实现兼容测试和正式    待修改 ***
	 //之后山东给域名后把图片把img文件夹扔进去  删除前面路径的一个img/即可使用
	 let rul_img = ''
	// #ifdef H5
	rul_img = '/static';
	// #endif
	// #ifdef MP
	rul_img = 'https://grzq-oss.wajx.top/static';
	// #endif

	return rul_img;
}


//地址判断https://grzqwx.wajx.top/static
const getDoMain = () => {
	var baseUrl = '';
	if (document.domain == 'grzqwx.wajx.top') {
		// baseUrl = 'http://talk_dev.jiudoujishi.com/';
		// baseUrl = 'http://develop.garden.kykykb.cn:7080';
		baseUrl = 'https://grzqwx.wajx.top';
	} else if (document.domain == 'grzq.wajx.top') {
		baseUrl = 'https://grzq.wajx.top';
	} else if (document.domain == 'localhost' || document.domain == '192.168.1.150') {
		baseUrl = 'https://grzqwx.wajx.top';
	} else {
		baseUrl = 'http://grzqwx.wajx.top' + document.domain + "";
	}
	return baseUrl;
}

//获取请求时的baseurl  目前只有正式环境修改了。  域名和请求地址为不同的域名目前
const requestBaseUrl = () => {
	var refBaseUrl = '';
	if (document.domain == 'grzq.wajx.top') {
		// refBaseUrl = 'http://talk_dev.jiudoujishi.com/';
		refBaseUrl = 'https://grzq.wajx.top'; //测试环境请求地址 => https协议
	} else if (document.domain == 'grzqwx.wajx.top') {
		refBaseUrl = 'https://grzqwx.wajx.top'; //正式环境请求地址 =>  https协议
	} else if (document.domain == 'localhost' || document.domain == '192.168.1.150') {
		// refBaseUrl = 'https://v1.kykykb.cn';
		refBaseUrl = 'https://grzqwx.wajx.top';
	} else {
		refBaseUrl = 'http://' + document.domain + "";
	}
	return refBaseUrl;
}


//获取当前年
const getCurrentYear = () => {
	return new Date().getFullYear();
}

//获取当前月
const getCurrentMonth = () => {
	var currentDate = new Date();
	var currentMonth = currentDate.getMonth() + 1;
	return currentMonth;
}
const parseFloatFixed=(num=0,isThisMonth= true)=>{
	let number = 0;
	if (!isThisMonth){
		number = '';
	}else {
		if (num != 0) {
			number = parseFloat(num).toFixed(2);
		}
	}
	return number;
}
const parseIntFixed=(num=0,isThisMonth= true)=>{
	let number = 0;
	number = parseInt(num);

	return number;
}

export default {
	_empty,
	prePage,
	isWx,
	countdownTime1,
	countdownTime,
	today,
	getDate,
	getDateHM,
	strToTimestamp,
	showToast,
	navTo,
	redirectTo,
	getBase64Image,
	countdownTime2,
	copyFunc,
	calcCharactersNumber,
	getDoMain,
	requestBaseUrl,
	objKeySort,
	getSigns,
	navBack,
	calcRequestParams,
	imgUrl,
	getMenuButtonBounding,
	getPageWidth,
	calcElementInfo,
	calcPhoneNumber,
	timeChange,
	getCurrentYear,
	parseFloatFixed,
	parseIntFixed,
	getCurrentMonth
};
